package com.carey.blog.repository.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import com.carey.blog.framework.latke.Keys;
import com.carey.blog.framework.latke.Latkes;
import com.carey.blog.framework.latke.RunsOnEnv;
import com.carey.blog.framework.latke.cache.Cache;
import com.carey.blog.framework.latke.cache.CacheFactory;
import com.carey.blog.framework.latke.repository.RepositoryException;
import com.carey.blog.framework.latke.repository.SortDirection;
import com.carey.blog.framework.latke.repository.gae.AbstractGAERepository;
import com.carey.blog.model.Page;
import com.carey.blog.repository.PageRepository;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

/**
 * Page Google App Engine repository.
 * 
 */
public final class PageGAERepository extends AbstractGAERepository implements
		PageRepository {

	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger
			.getLogger(PageGAERepository.class.getName());
	/**
	 * Cache.
	 */
	private static final Cache<String, Object> CACHE;

	static {
		final RunsOnEnv runsOnEnv = Latkes.getRunsOnEnv();
		if (!runsOnEnv.equals(RunsOnEnv.GAE)) {
			throw new RuntimeException(
					"GAE repository can only runs on Google App Engine, please "
							+ "check your configuration and make sure "
							+ "Latkes.setRunsOnEnv(RunsOnEnv.GAE) was invoked before "
							+ "using GAE repository.");
		}

		CACHE = CacheFactory.getCache("PageGAERepositoryCache");
	}

	@Override
	public String getName() {
		return Page.PAGE;
	}

	@Override
	public JSONObject getByPermalink(final String permalink) {
		final Query query = new Query(getName());
		query.addFilter(Page.PAGE_PERMALINK, Query.FilterOperator.EQUAL,
				permalink);
		final PreparedQuery preparedQuery = getDatastoreService()
				.prepare(query);
		final Entity entity = preparedQuery.asSingleEntity();
		if (null == entity) {
			return null;
		}

		final Map<String, Object> properties = entity.getProperties();

		return new JSONObject(properties);
	}

	@Override
	public int getMaxOrder() throws RepositoryException {
		final Query query = new Query(getName());
		query.addSort(Page.PAGE_ORDER, Query.SortDirection.DESCENDING);
		final PreparedQuery preparedQuery = getDatastoreService()
				.prepare(query);
		final List<Entity> links = preparedQuery.asList(FetchOptions.Builder
				.withDefaults());
		if (links.isEmpty()) {
			return -1;
		}

		try {
			final Map<String, Object> properties = links.get(0).getProperties();
			return new JSONObject(properties).getInt(Page.PAGE_ORDER);
		} catch (final JSONException e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);
			throw new RepositoryException(e);
		}
	}

	@Override
	public JSONObject getByOrder(final int order) {
		final Query query = new Query(getName());
		query.addFilter(Page.PAGE_ORDER, Query.FilterOperator.EQUAL, order);
		final PreparedQuery preparedQuery = getDatastoreService()
				.prepare(query);
		final Entity entity = preparedQuery.asSingleEntity();
		if (null == entity) {
			return null;
		}

		final Map<String, Object> properties = entity.getProperties();

		return new JSONObject(properties);
	}

	@Override
	public List<JSONObject> getPages() throws RepositoryException {
		final String cacheKey = "[pages]";
		@SuppressWarnings("unchecked")
		List<JSONObject> ret = (List<JSONObject>) CACHE.get(cacheKey);
		if (null != ret) {
			LOGGER.log(Level.FINEST, "Got the pages from cache");
		} else {
			ret = new ArrayList<JSONObject>();
			final com.carey.blog.framework.latke.repository.Query query = new com.carey.blog.framework.latke.repository.Query()
					.addSort(Page.PAGE_ORDER, SortDirection.ASCENDING);
			final JSONObject result = get(query);

			try {
				ret = com.carey.blog.framework.latke.util.CollectionUtils
						.jsonArrayToList(result.getJSONArray(Keys.RESULTS));
			} catch (final JSONException e) {
				LOGGER.log(Level.SEVERE, e.getMessage(), e);
				throw new RepositoryException(e);
			}

			CACHE.put(cacheKey, ret);

			LOGGER.log(Level.FINEST, "Got the pages, then put it into cache");
		}

		return ret;
	}

	/**
	 * Gets the {@link PageGAERepository} singleton.
	 * 
	 * @return the singleton
	 */
	public static PageGAERepository getInstance() {
		return SingletonHolder.SINGLETON;
	}

	/**
	 * Private default constructor.
	 */
	private PageGAERepository() {
	}

	/**
	 * Singleton holder.
	 * 
	 */
	private static final class SingletonHolder {

		/**
		 * Singleton.
		 */
		private static final PageGAERepository SINGLETON = new PageGAERepository();

		/**
		 * Private default constructor.
		 */
		private SingletonHolder() {
		}
	}
}
